package com.bbs.aop;

import com.bbs.anno.MyLog;
import com.bbs.entity.LogEntity;
import com.bbs.service.LogEntityService;
import com.bbs.util.UserHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;

@Aspect//标注这是一个切面类
@Component
public class LogAspect {
    @Autowired
    LogEntityService logEntityService;
//该方法用于切入执行的方法，获取异常信息
    //@Around("@annotation(com.bbs.anno.MyLog)")
    public Object around(ProceedingJoinPoint joinPoint, com.bbs.anno.MyLog mylog) throws Throwable {
//获取开始时间
        long start = System.currentTimeMillis();
        //定义执行结果
        Object result=null;
        //定义异常
       Throwable e=null;
        try{
           result= joinPoint.proceed();
           return result;
        } catch (Throwable ex) {
           e=ex;
           throw ex;
        }
        finally {
        //添加日志到日志记录里
            saveLog(joinPoint,start,result,e,mylog);
        }

    }

    public void saveLog(ProceedingJoinPoint joinPoint,long start,Object result,Throwable throwable,MyLog myLog) {

        LogEntity log = new LogEntity();
        log.setModule(myLog.module());
        log.setOperation(myLog.value());
        log.setResult(result.toString());
        log.setException(String.valueOf(throwable));
        Long id = UserHolder.getUser().getId()!=null? UserHolder.getUser().getId():null;
        log.setUserId(id);
        log.setExecutionTime(System.currentTimeMillis()-start);

        //TODO 获取请求参数
        if (myLog.saveParams()) {
            log.setParams((Arrays.toString(joinPoint.getArgs())));
        }
        //添加
        logEntityService.save(log);
    }
}
